package com.atguigu.gmall.user.controller;


import brave.http.HttpServerRequest;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserServcie;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserServcie userServcie;


    /**
     * 用户登录
     * @return
     */
    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) throws JsonProcessingException {

        //登陆成功要返回这种数据
        Map<String,String> loginData = userServcie.login(userInfo,request);

        //结论:登录成功后返回token和nickName
        if (loginData == null){
            //用户登陆失败
            return Result.build(null, ResultCodeEnum.LOGIN_FAIL);
        }else {
            return Result.ok(loginData);
        }
    }


    /**
     * 用户退出
     * @return
     * token: 23cef5ac37294f03a05aed124bd0cc3e
     */
    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader(value = "token") String token){

        userServcie.logout(token);
        //只要我们响应推出成功,前端就会自动删除cookie
        return Result.ok();
    }
}
